﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;

namespace Utilities.Database
{
    public static class SqlHelper
    {
        public static List<T> ToList<T>(this DataTable dt) where T : class,new()
        {
            List<PropertyInfo> prlist = new List<PropertyInfo>();
            Type t = typeof(T);
            Array.ForEach<PropertyInfo>(t.GetProperties(), p =>
            {
                if (dt.Columns.IndexOf(p.Name) != -1)
                    prlist.Add(p);
            });
            List<T> oblist = new List<T>();
            foreach (DataRow row in dt.Rows)
            {
                T ob = new T();
                prlist.ForEach(p =>
                {
                    if (row[p.Name] != DBNull.Value)
                    {
                        p.SetValue(ob, Convert.ChangeType(row[p.Name], row[p.Name].GetType()), null);
                    }
                });
                oblist.Add(ob);
            }
            return oblist;

        }
    }
}
